﻿/*-----------------------------------------------------------------------
 * <copyright file="OPIDSelectChildWindow.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang jun</author>
 * <summary>
 *          OP信息查询子窗体
 *          
 *      作成日：05/21/2010
 *          
 *  子窗体返回列表值： 
 *   ClientDataList.SelOpIDList（选择部分OP时，记录OPID  -全局-  没有单引号，没有逗号）
 *   ClientDataList.CheckOpUnitList（ ① 选择所有的OP，记录OP所在组号
 *                                    ② 选择部分UNIT时，记录UNIT号
 *                                      -全局- 没有单引号，没有逗号）
 *              05/25/2010 修改 将子窗体从OPEntrySpeedQuery文件夹下移出至CommonWin文件夹内
 *                              变为选择OP的公用选择窗口
 *              06/02/2010 修改 ClientDataList.SelOpIDList变为没有单引号的形式（服务端改为存储过程）
 *
 *              07/08/2010 修改 SV和QC没有“选择一组或多组”选项 (现场)
 *              
 *              08/19/2010 增加 selectStatus 全局变量，记录单选选项信息
 * </summary>
 *----------------------------------------------------------------------- 
 */
namespace Orid.Management.Statistics.OperatorUnitMangement.Common.Window
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Input;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.WCFCommonQueryRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;

    /// <summary>
    /// OP子查询窗体
    /// OPIDSelectChildWindow
    /// </summary>
    public partial class OPIDSelectChildWindow : System.Windows.Controls. ChildWindow
    {        
        /// <summary>
        /// 消息子窗口
        /// messbox
        /// </summary>
        private childWindow.MessageBox messbox = null;
        /// <summary>
        /// 服务引用 (查询OP信息用)
        /// wcfClient
        /// </summary>
        private WCFCommonQueryClient wcfClient = null;

        /// <summary>
        /// 日志服务定义
        /// wcfLogClient
        /// </summary>
        private WCFLog4Ref.WCFLog4Client wcfLogClient = null;
                
        /// <summary>
        /// 从返回的服务中取得UNIT组号，
        /// 为多个CHECK命名用。
        /// </summary>
        private List<string> unitAllList = new List<string>();        
        
        /// <summary>
        /// 分页控件
        /// PagedCollectionView
        /// </summary>
        private PagedCollectionView pcv;

        /// <summary>
        /// grid数
        /// pageCount
        /// </summary>
        private int pageCount = 30;

        /// <summary>
        /// 记录单选选项信息
        /// </summary>
        /// <value>08/19/2010 增加</value>
        private string selectStatus = string.Empty;
        public string SelectStatus
        {
            get { return selectStatus; }
            set { selectStatus = value; }
        }
        
        /// <summary>
        /// ObservableCollection当数据增加或册除时，同时更新。
        /// 为收到返回值的dagagrid的checkbox增加了一个CHECK状态字段
        /// </summary>
        ObservableCollection<ClientSelectOPInforDataList> clientSelectOPInofrList = new ObservableCollection<ClientSelectOPInforDataList>();

        /// <summary>
        /// 构造函数 
        /// OPIDSelectChildWindow
        /// </summary>
        public OPIDSelectChildWindow()
        {
            InitializeComponent();

            // 引用主题
            ((App)Application.Current).SetTheme((Grid)LayoutRoot);

            this.dgOPIDSelList.HeadersVisibility = DataGridHeadersVisibility.All;//同时显示DataGrid的行头与列头

            this.messbox = new childWindow.MessageBox();
            this.wcfLogClient = Wcf.Service.Log4;

            // 搜索框键盘 KeyDown事件（委托）
            this.tbInput.KeyDown += new KeyEventHandler(this.TbInput_KeyDown);

            this.OKButton.Click += new RoutedEventHandler(this.OKButton_Click);
            this.CancelButton.Click += new RoutedEventHandler(this.CancelButton_Click);

            this.Loaded += new RoutedEventHandler(this.OPIDSelectChildWindow_Loaded);
            this.Closed += new EventHandler(OPIDSelectChildWindow_Closed);

            // 按组别分组
            this.cbGroup.Checked += new RoutedEventHandler(this.CbGroup_Checked);
            this.cbGroup.Unchecked += new RoutedEventHandler(this.CbGroup_Unchecked);

            // 择选所有的OP
            this.cbAllOP.Checked += new RoutedEventHandler(this.CbAllOP_Checked);
           
            // 是否选多个分组
            this.cbSelectUnit.Click += new RoutedEventHandler(this.CbSelectUnit_Click);

            // 选择一个或多个OP
            this.cbAnyOP.Click += new RoutedEventHandler(this.CbAnyOP_Click);
        }
        
        /// <summary>
        /// 页面载入
        /// OPIDSelectChildWindow_Loaded
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void OPIDSelectChildWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                this.MyIsEnabled(false);
                
                // 07/07/2010 -- edit
                // 如果是SSV才显示这一项
                //如果有多个组，可以选择以下单个或多个组
                this.cbSelectUnit.Visibility = Visibility.Collapsed;

                this.dpDGPage.DataContext = null;
                this.dgOPIDSelList.ItemsSource = null;

                ClientDataList.SelOpIDList.Clear();
                ClientDataList.CheckOpUnitList.Clear();
                ManualTextWrapping.Children.Clear();
                
                this.tbInput.IsEnabled = true;
                this.cbAnyOP.IsChecked = true;

                this.cbAllOP.IsEnabled = false;
                this.cbAllOP.IsChecked = false;
                this.cbGroup.IsChecked = false;

                this.tbInput.Text = string.Empty;

                //  07/08/2010 -- add 
                selectSVOPList();
                
            }
            catch (Exception ex)
            {
                Common.FunctionList.FunctionClass.ShowMessageBox(
                  this.messbox,
                  1,
                  "提示",
                  ex.Message.ToString(),
                  Colors.Gray,
                  true,
                  Visibility.Visible,
                  Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 关闭事件
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        void OPIDSelectChildWindow_Closed(object sender, EventArgs e)
        {
            this.dgOPIDSelList.ItemsSource = null;
            this.dpDGPage.DataContext = null;
        }

        /// <summary>
        /// 确定按钮(记录被选择的部分OPID )
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {

            // 已选择的部分OPID(单选按钮)
            if (this.cbAnyOP.IsChecked == true) 
            {
                if (this.clientSelectOPInofrList.Count > 0)
                {
                    ClientDataList.SelOpIDList.Clear();

                    // 将选中的OPID号加入SelOpIDList中
                    ClientDataList.SelOpIDList = (from sl in clientSelectOPInofrList
                                                  where sl.SelectIDCheck == true
                                                  select sl.OpetatorID).Distinct<string>().ToList<string>();
                }
            }

            // 已选择的部分组号
            if (this.cbSelectUnit.IsChecked == true)
            {
                // ClientDataList.CheckOpUnitList（全局） 返回被选中的UNIT信息
                ClientDataList.CheckOpUnitList.Clear();
                
                // **************CheckBox****************
                // 判断哪个CHECKBOX是选中状态，并将值
                // 传给ClientDataList.CheckOpUnitList
                CheckBox checkbox;
                for (int i = 0; i < this.ManualTextWrapping.Children.Count; i++) 
                {
                    checkbox = ManualTextWrapping.Children[i] as CheckBox; 

                    // 如果类型不一致则返回null
                    if (checkbox != null && checkbox.IsChecked == true) 
                    {
                        // 不用加引号和逗号
                        ClientDataList.CheckOpUnitList.Add(checkbox.Content.ToString().Trim());
                    }
                } 
                // **************************************
            }

            this.MyIsEnabled(false); 
            this.dgOPIDSelList.ItemsSource = null;
            this.dpDGPage.DataContext = null;
            this.DialogResult = true;
        }

        /// <summary>
        /// 取消
        /// CancelButton_Click
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {            
            ClientDataList.SelOpIDList.Clear();
            ClientDataList.CheckOpUnitList.Clear();

            this.MyIsEnabled(false); 
            this.dgOPIDSelList.ItemsSource = null;
            this.dpDGPage.DataContext = null;
            this.DialogResult = false;
        }

        #region  按组别分组

        /// <summary>
        /// 按组别分组(未选中状态)
        /// CbGroup_Unchecked
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void CbGroup_Unchecked(object sender, RoutedEventArgs e)
        {
            if (this.clientSelectOPInofrList.Count > 0)
            {
                this.dgOPIDSelList.ItemsSource = null;
                this.pcv = new PagedCollectionView(this.clientSelectOPInofrList);
                this.pcv.PageSize = this.pageCount;
                this.dgOPIDSelList.ItemsSource = this.pcv;
                this.dpDGPage.DataContext = this.pcv;
                this.dpDGPage.IsEnabled = true;
            }
        }

        /// <summary>
        /// 按组别分组(选中状态)
        /// CbGroup_Checked
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void CbGroup_Checked(object sender, RoutedEventArgs e)
        {
            if (this.clientSelectOPInofrList.Count > 0)
            {
                // 按组别分组
                // 通过 PagedCollectionView 的 GroupDescriptions 设置需要分组的字段，
                // 绑定到 DataGrid 后，DataGrid会自动对数据做分组显示
                
                this.dgOPIDSelList.ItemsSource = null;
                PagedCollectionView pcvGroup = new PagedCollectionView(this.clientSelectOPInofrList);
                pcvGroup.GroupDescriptions.Add(new PropertyGroupDescription("Unit"));
                pcvGroup.PageSize = 10000;
                this.dgOPIDSelList.ItemsSource = pcvGroup;
                this.dpDGPage.IsEnabled = false;
            }
        }
        #endregion  按组别分组

        #region 搜索框 按OP姓名或ID搜索（实现）
        /// <summary>
        /// 搜索框 按OP姓名或ID搜索（实现）
        /// 当前登录SV或SSV下的所有OP
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of  KeyEventArgs</param>
        private void TbInput_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    selectSVOPList();
                }
            }
            catch (Exception ex)
            {
                Common.FunctionList.FunctionClass.ShowMessageBox(
                  this.messbox,
                  1,
                  "提示",
                  ex.Message.ToString(),
                  Colors.Gray,
                  true,
                  Visibility.Visible,
                  Visibility.Collapsed);
            }
        }
        #endregion 搜索框 按OP姓名或ID搜索（实现）

        #region  搜索框搜索当前SV的OP信息的结果

        /// <summary>
        /// 搜索框搜索当前SV的OP信息的结果
        /// 用于在DATAGEID中显示
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of SelectSVOPInforCompletedEventArgs</param>
        private void WCFClient_SelectSVOPInforCompleted(object sender, SelectSVOPInforCompletedEventArgs e)
        {
            try
            {
                this.tbInput.IsEnabled = true;

                if (e.Error == null)
                {
                    // 将服务端的数据转换成ObservableCollection<T>，当数据增加或修改时，同时更新。
                    if (e.Result.Count > 0)
                    {
                        this.clientSelectOPInofrList.Clear();
                        foreach (WCFServers.WCFCommonQueryRef.SelectOPInforDataList item in e.Result)
                        {
                            this.clientSelectOPInofrList.Add(new ClientSelectOPInforDataList()
                            {
                                // check默认值
                                SelectIDCheck = false,
                                SvID = FunctionClass.MyIsNullOrEmpty(item.SvID, null),
                                OpetatorID = FunctionClass.MyIsNullOrEmpty(item.OpID, null),
                                OpName = FunctionClass.MyIsNullOrEmpty(item.OpName, null),
                                Unit = FunctionClass.MyIsNullOrEmpty(item.Unit, null)
                            });
                        }

                        // 如果不是 SV或QC 显示cbSelectUnit --07/08/2010  edit
                        if (!(ClientUserInfor.RoleName.ToUpper().Trim().Equals("SV")||ClientUserInfor.RoleName.ToUpper().Trim().Equals("QC")))
                        {
                            // 如果有多个分组，将分组加入列表UnitAllList中
                            // 为动态生成CHECK命名用
                            this.unitAllList.Clear();

                            // 公有，全局
                            this.unitAllList = (from unit in clientSelectOPInofrList
                                                orderby unit.Unit
                                                select unit.Unit).Distinct<string>().ToList<string>();

                            // *************CheckBox********************//
                            // 动态生成CHECKBOX，并给CONTEXT赋值（组名）。
                            ManualTextWrapping.Children.Clear();
                            ManualTextWrapping.Visibility = Visibility.Collapsed;
                            if (this.unitAllList.Count > 0)
                            {
                                for (int i = 0; i < this.unitAllList.Count; i++)
                                {
                                    CheckBox cb = new CheckBox();
                                    cb.Content = this.unitAllList[i].ToString();
                                    cb.IsChecked = false;
                                    cb.Margin = new Thickness(10, 3, 0, 5);
                                    this.ManualTextWrapping.Children.Add(cb);
                                }
                            }
                            // ***************************************** 

                            this.cbSelectUnit.Visibility = Visibility.Visible;
                        }
                        else
                        {
                            this.cbSelectUnit.Visibility = Visibility.Collapsed;
                        }
                      
                        this.pcv = new PagedCollectionView(this.clientSelectOPInofrList);
                        this.pcv.PageSize = this.pageCount;

                        this.dpDGPage.IsEnabled = true;
                        this.dgOPIDSelList.ItemsSource = this.pcv;
                        this.dpDGPage.DataContext = this.pcv;

                        this.MyIsEnabled(true);
                        this.dgOPIDSelList.IsEnabled = true;
                    }
                    else
                    {
                        this.dgOPIDSelList.ItemsSource = null;
                        this.dpDGPage.DataContext = null;
                        this.MyIsEnabled(false);
                        throw new Exception("查询子窗体中没有可显示的数据");
                    }
                }
                else
                {
                    throw (new Exception(e.Error.Message.ToString()));
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + " OP信息查询子窗体 OPIDSelectChildWindow " + ex.Message.ToString());
                Common.FunctionList.FunctionClass.ShowMessageBox(
                    this.messbox,
                    1,
                    "提示",
                    ex.Message.ToString(),
                    Colors.Gray,
                    true,
                    Visibility.Visible,
                    Visibility.Collapsed);
                return;
            }
        }

        #endregion 搜索框搜索当前SV的OP信息的结果

        #region 查询选择项

        #region 选择/不选择所有的OP (实现)
        /// <summary>
        /// 选择所有的OP (实现)
        /// CbAllOP_Checked
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void CbAllOP_Checked(object sender, RoutedEventArgs e)
        {
            this.SetControlOfWrappingStatus(false);
            
            //记录选择状态
            SelectStatus = string.Empty;
            selectStatus = "Select All Operators";

            // 记录OP所在组号
            if (this.cbAllOP.IsEnabled == true) 
            {
                ClientDataList.CheckOpUnitList.Clear();

                // 公有，全局
                ClientDataList.CheckOpUnitList = (from opunit in clientSelectOPInofrList
                                   select opunit.Unit).Distinct<string>().ToList<string>();
            }

            this.dgOPIDSelList.IsEnabled = false;
        }

        #endregion 择选所有的OP (实现)

        #region 是否选多个分组
        /// <summary>
        /// 是否选多个分组
        /// CbSelectUnit_Click
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void CbSelectUnit_Click(object sender, RoutedEventArgs e)
        {
            //记录选择状态
            SelectStatus = string.Empty;
            selectStatus = "Select One Or More Unit";

            if (((RadioButton)sender).IsChecked == true)
            {
                this.dgOPIDSelList.IsEnabled = false;
                this.SetControlOfWrappingStatus(true); 
                ClientDataList.CheckOpUnitList.Clear();
            }
            else 
            {
                this.SetControlOfWrappingStatus(false); 
            }
        }
        #endregion 是否选多个分组

        #region  选择一个或多个OP
        /// <summary>
        /// 选择一个或多个OP
        /// CbAnyOP_Click
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void CbAnyOP_Click(object sender, RoutedEventArgs e)
        {
            //记录选择状态
            SelectStatus = string.Empty;
            selectStatus = "Select One Or More Operator";

            if (((RadioButton)sender).IsChecked == true)
            {
                this.dgOPIDSelList.IsEnabled = true;
                this.SetControlOfWrappingStatus(false); 
                ClientDataList.SelOpIDList.Clear();
            }
        }

        #endregion  选择一个或多个OP

        #endregion 查询选择项

        #region 控件状态

        /// <summary>
        /// 控制“选择所有的OP的CHECKBOX”
        /// 和“按组别分组的BUTTON”
        /// </summary>
        /// <param name="bis"> bis type of bool </param>
        private void MyIsEnabled(bool bis) 
        {
            // 选择所有的OP
            this.cbAllOP.IsEnabled = bis;
            // 按组别分组的
            this.cbGroup.IsEnabled = bis;
            //选择一个或几个OP
            this.cbAnyOP.IsEnabled = bis;
            //如果有多个组，可以选择以下单个或多个组
            this.cbSelectUnit.IsEnabled = bis;

            this.dgOPIDSelList.IsEnabled = bis;
            this.dpDGPage.IsEnabled = bis;
        }

        /// <summary>
        /// Wrapping是否可视
        /// Wrapping里的所有控件的状态设定
        /// </summary>
        /// <param name="bval">Wrapping 布尔类型 是否可视</param>
        private void SetControlOfWrappingStatus(bool bval) 
        {
            // Wrapping可视
            if (bval == true)
            {
                this.ManualTextWrapping.Visibility = Visibility.Visible;
            }           
            else 
            { 
                // Wrapping不可视,内部控件状态为没选择状态
                this.ManualTextWrapping.Visibility = Visibility.Collapsed;
                CheckBox checkbox;
                for (int i = 0; i < this.ManualTextWrapping.Children.Count; i++)
                {
                    checkbox = ManualTextWrapping.Children[i] as CheckBox; 
                    checkbox.IsChecked = false;
                } 
            }
        }

        #endregion 控件状态     

        #region 判断前登录的SV或是SSV,并显示相应的所有OP信息
        /// <summary>
        /// 判断前登录的SV或是SSV,并显示相应的所有OP信息
        /// 07/08/2010 -- add 
        /// </summary>
        void selectSVOPList()
        {
            this.wcfClient = Wcf.Service.CommonQuery;
            //搜索框 查询 服务委托
            this.wcfClient.SelectSVOPInforCompleted += new EventHandler<SelectSVOPInforCompletedEventArgs>(this.WCFClient_SelectSVOPInforCompleted);

            // 判断有没有当前登录的SV或是SSV的登录信息
            if (!String.IsNullOrEmpty(Common.FunctionList.ClientUserInfor.UserName))
            {
                //如果搜索框中没有记录，查询所有OP信息
                if (string.IsNullOrEmpty(this.tbInput.Text))
                {
                    this.wcfClient.SelectSVOPInforAsync(Common.FunctionList.ClientUserInfor.UserName, "%");
                    this.tbInput.IsEnabled = false;
                }
                else
                {
                    //有记录，按OPID或是OP姓名查询
                    this.wcfClient.SelectSVOPInforAsync(Common.FunctionList.ClientUserInfor.UserName, this.tbInput.Text.Trim());
                    this.tbInput.IsEnabled = false;
                }
            }
            else
            {
                throw new Exception("当前用户信息有误");
            }
        }
        #endregion

        


    }
}

